package nio.groupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * description:
 * author:zt
 * date:2021-09-13
 */
public class Server {
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private static final int PORT = 6667;

    public Server() {
        try{
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //监听
    public void listen(){
        try{
            while (true){
                int count = selector.select(2000);
                if (count > 0){ //有事件要处理
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        if (key.isAcceptable()){
                            SocketChannel sc = serverSocketChannel.accept();
                            sc.configureBlocking(false);
                            sc.register(selector,SelectionKey.OP_READ);
                            System.out.println(sc.getRemoteAddress() + "：上线");
                        }
                        if (key.isReadable()){
                            readData(key);
                        }
                        iterator.remove();
                    }

                }else {
                    System.out.println("等待连接");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }

    //读取客户端消息
    public void readData(SelectionKey key){
        SocketChannel channel = null;
        try{
            channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer); //channel读到buffer
            if (count > 0){
                String msg = new String(buffer.array());
                System.out.println(channel.getRemoteAddress()+"发送消息："+msg);
                //转发
                sendToOther(msg,channel);
            }
        }catch (IOException e){
            try {
                System.out.println(channel.getRemoteAddress()+"离线了...");
                key.cancel();  //取消注册
                channel.close();  //关闭通道
            }catch (IOException e2){
                e2.printStackTrace();
            }
        }
    }

    //转发消息给其他用户
    private void sendToOther(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中...");
        //遍历 所有注册到selector 上的 socketChannel 并排除自己
        for (SelectionKey key : selector.keys()) {
            //通过key 取出对应的socketChannel
            Channel channel = key.channel();
            if (channel instanceof SocketChannel && channel != self){
                SocketChannel dest = (SocketChannel) channel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                dest.write(buffer); //buffer数据写入通道
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.listen();
    }
}
